#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/12/23 16:50
# @Author  : Beam
# @Site    : 
# @File    : redisinfo.py
# @Software: PyCharm


from django.shortcuts import render,HttpResponse
from backend import models
from django.views import View
from func import redisconnect
import json

class RedisInfo(View):

	def get(self,request,*args,**kwargs):
		username = request.session.get('username')
		redisinfos = models.RedisConfig.objects.all().values('id','project__projectname','redisname','hostname','hostip','port','environment__pathname','dbcount','remarks')
		return render(request, 'redisinfo.html',{'redisinfos':redisinfos,'username':username})

	def post(self,request,*args,**kwargs):
		result = {'isFalg':False,'redisinfo':None,'rediskeys':None}
		redisId = request.POST.get('redisId')
		robj = models.RedisConfig.objects.get(id=redisId)
		try:
			obj = redisconnect.ConRedis(robj.hostip,robj.port,robj.auth)
			redisinfo = obj.info()
			rediskeys = {}
			for i in range(0,int(robj.dbcount)):
				obj = redisconnect.ConRedis(robj.hostip, robj.port, robj.auth,i)
				keyinfo = obj.keys()
				if keyinfo:
					rediskeys[i] = str(keyinfo)
			result['isFalg'] = True
			result['redisinfo'] = redisinfo
			if rediskeys:
				result['rediskeys'] = rediskeys
			return HttpResponse(json.dumps(result,ensure_ascii=False))
		except:
			result['message'] = '由于连接方在一段时间后没有正确答复或连接的主机没有反应，连接尝试失败。请联系管理员确认配置是否正确以及是否在局域网内。'
			return HttpResponse(json.dumps(result, ensure_ascii=False))
